package org.dromara.creditcard.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.mybatis.core.page.PageUtils;
import org.dromara.creditcard.domain.BdCity;
import org.dromara.creditcard.domain.BdDistrict;
import org.dromara.creditcard.domain.BdProvince;
import org.dromara.creditcard.service.IBdCityService;
import org.dromara.creditcard.service.IBdDistrictService;
import org.dromara.creditcard.service.IBdProvinceService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.creditcard.domain.CreateAgent;
import org.dromara.creditcard.service.ICreateAgentService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 代理
 *
 * @author Mr.Zhou
 * @date 2023-12-14
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/credit/agent")
public class CreateAgentController extends BaseController {

    private final ICreateAgentService createAgentService;
    private final IBdProvinceService provinceService;
    private final IBdCityService cityService;
    private final IBdDistrictService districtService;

    /**
     * 查询代理列表
     */
    @SaCheckPermission("credit:agent:list")
    @GetMapping("/list")
    public TableDataInfo<CreateAgent> list(CreateAgent createAgent, PageQuery pageQuery) {
        QueryWrapper<CreateAgent> qw = new QueryWrapper<>();

        TableDataInfo<CreateAgent> td = PageUtils.buildDataInfo(createAgentService.page(PageUtils.buildPage(),qw));
        List<CreateAgent> list = td.getRows();
        for (CreateAgent agent : list) {
            String areaName = "";
            BdProvince province = provinceService.getById(agent.getProvId());
            if(province!=null){
                areaName += province.getProvinceName();
            }

            BdCity city = cityService.getById(agent.getCityId());
            if(city != null){
                areaName += "-" +city.getCityName();
            }

            BdDistrict district = districtService.getById(agent.getDistrictId());
            if(district != null){
                areaName += "-" +district.getDistrictName();
            }
            agent.setAreaName(areaName);

        }
        return td;
    }

    /**
     * 导出代理列表
     */
    @SaCheckPermission("credit:agent:export")
    @Log(title = "代理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(CreateAgent createAgent, HttpServletResponse response) {
        List<CreateAgent> list = createAgentService.list();
        ExcelUtil.exportExcel(list, "代理", CreateAgent.class, response);
    }

    /**
     * 获取代理详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("credit:agent:query")
    @GetMapping("/{id}")
    public R<CreateAgent> getInfo(@NotNull(message = "主键不能为空") @PathVariable Integer id) {
        CreateAgent agent = createAgentService.getById(id);
        if(agent!= null){
            String[] areas = { String.valueOf(agent.getProvId()),String.valueOf(agent.getCityId()),String.valueOf(agent.getDistrictId()) };
            agent.setProvinceArray(areas);

            String areaName = "";
            BdProvince province = provinceService.getById(agent.getProvId());
            if(province!=null){
                areaName += province.getProvinceName();
            }

            BdCity city = cityService.getById(agent.getCityId());
            if(city != null){
                areaName += city.getCityName();
            }

            BdDistrict district = districtService.getById(agent.getDistrictId());
            if(district != null){
                areaName += district.getDistrictName();
            }
            agent.setAreaName(areaName);

        }
        return R.ok(agent);
    }

    /**
     * 新增代理
     */
    @SaCheckPermission("credit:agent:add")
    @Log(title = "代理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CreateAgent createAgent) {

        if(createAgent.getProvinceArray() != null&&createAgent.getProvinceArray().length == 3){
            createAgent.setProvId(Integer.parseInt(createAgent.getProvinceArray()[0]));
            createAgent.setCityId(Integer.parseInt(createAgent.getProvinceArray()[1]));
            createAgent.setDistrictId(Integer.parseInt(createAgent.getProvinceArray()[2]));
        }

        createAgent.setCreateTime(new Date());

        return toAjax(createAgentService.save(createAgent));
    }

    /**
     * 修改代理
     */
    @SaCheckPermission("credit:agent:edit")
    @Log(title = "代理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CreateAgent createAgent) {

        if(createAgent.getProvinceArray()!=null&&createAgent.getProvinceArray().length==3){
            createAgent.setProvId(Integer.parseInt(createAgent.getProvinceArray()[0]));
            createAgent.setCityId(Integer.parseInt(createAgent.getProvinceArray()[1]));
            createAgent.setDistrictId(Integer.parseInt(createAgent.getProvinceArray()[2]));
        }
        return toAjax(createAgentService.updateById(createAgent));
    }

    /**
     * 删除代理
     *
     * @param ids 主键串
     */
    @SaCheckPermission("credit:agent:remove")
    @Log(title = "代理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Integer[] ids) {
        return toAjax(createAgentService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
